package com.kjlink.widget.monitoring.schedule.handle;

import com.kjlink.widget.monitoring.config.MonitorConfigParams;
import com.kjlink.widget.monitoring.entity.MonitorEventBatch;
import com.kjlink.widget.monitoring.repository.MonitorEventBatchRepository;
import com.kjlink.widget.monitoring.service.EventBatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 描述:
 * 定时任务处理器
 *
 * @author Vic.xu
 * @since 2025-08-08 15:59
 */
@Slf4j
@Component
public class MonitorEventTaskHandler {

    // 配置参数
    @Resource
    private MonitorConfigParams monitorConfigParams;

    /**
     * 上一次执行过期事件处理任务: 检测事件批次的时间点
     */
    public static LocalDateTime lastCheckEndTime = null;

    @Resource
    private MonitorEventBatchRepository monitorEventBatchRepository;



    @Resource
    private EventBatchService eventBatchService;

    /**
     * 标记过期事件批次
     */
    public void markExpiredEventBatch() {
        LocalDateTime now = LocalDateTime.now();
        // 超过N小时未处理 或者失败的 的批次 则标记为过期
        LocalDateTime endTime = now.minus(monitorConfigParams.getExpireMinutes(), ChronoUnit.MINUTES);
        int expireInitialNumber = monitorEventBatchRepository.updateExpiredBatches(MonitorEventBatch.BatchStatus.expire,
                MonitorEventBatch.BatchStatus.initial,
                endTime, lastCheckEndTime);
        int expireFailNumber= monitorEventBatchRepository.updateExpiredBatches(MonitorEventBatch.BatchStatus.expire,
                MonitorEventBatch.BatchStatus.fail,
                endTime, lastCheckEndTime);
        log.info("Marked [{}] event batch expired ", (expireInitialNumber + expireFailNumber));
        // 不在维护 lastCheckEndTime, 防止因为状态变更 导致 数据永远无法标记为过期
//        lastCheckEndTime = endTime;

    }




}
